using System.Collections.Generic;
using System.Threading.Tasks;
using IntegratedMeasuring.Utils;
using IntegratedMeasuring.ViewModels.Scheme;
using SqlSugar;
using System;
using System.Linq;
using Tmds.DBus.Protocol;
using Dm.util;
using Avalonia.Input;

namespace IntegratedMeasuring.Storage;

/// <summary>
/// 基础数据存储操作工具类
/// 提供对基础数据库的增删改查操作
/// </summary>
public class BaseDataStorage : BaseStorage
{
    private static readonly BaseDataStorage _instance = new BaseDataStorage();

    private BaseDataStorage() : base($"DataSource={IntegratedMeasuring.ViewModels.Entity.GC.BaseDbFilePath}")
    {
    }

    /// <summary>
    /// 获取单例实例
    /// </summary>
    public static BaseDataStorage Instance => _instance;

    public override void InitRuntimeTables()
    {
        _db.DbMaintenance.CreateDatabase();
        _db.CodeFirst.InitTables<ProductionOrder>();
        _db.CodeFirst.InitTables<TestConditions>();
        _db.CodeFirst.InitTables<TestRecord>();
        _db.CodeFirst.InitTables<ProductInfo>();

        try
        {
            _db.Ado.ExecuteCommand("CREATE INDEX IF NOT EXISTS IX_ProductInfo_BarCode ON ProductInfo(BarCode)");
        }
        catch (Exception ex)
        {
            // 索引可能已存在，这是正常情况，不需要报错
        }
    }

    // 保存机种测试条件
    public async Task<bool> SaveTestConditionsAsync(TestConditions testConditions)
    {
        var blDel = false;
        // 查询机种名称是否有重复
        var exist = await QueryAsync<TestConditions>(x => x.Name == testConditions.Name);
        if (exist.Count != 0)
        {
            blDel = await DeleteAsync<TestConditions>(x => x.Name == testConditions.Name);
        }
        testConditions.Id = SnowFlakeSingle.Instance.NextId();
        var result = await InsertAsync(testConditions);
        return result;

    }

    // 加载测试文件列表
    public async Task<List<TestConditions>> LoadTestConditionsListAsync()
    {
        var testConditions = await QueryAllAsync<TestConditions>();
        return testConditions;
    }

    // 删除机种测试条件
    public async Task<bool> DeleteTestConditionsAsync(long id)
    {
        var result = await DeleteAsync<TestConditions>(x => x.Id == id);
        return result;
    }


    public  ProductionOrder GetLastUsedOrders()
    { 
        var order =  QueryFirstDesc<ProductionOrder>(x => true, "CreateTime");
        return order;
    }
    // 加载工单列表
    public async Task<List<ProductionOrder>> LoadProductionOrdersAsync()
    {
        var orders = await QueryAllAsync<ProductionOrder>();
        return orders;
    }

    // 通过工单号查询工单信息
    public async Task<ProductionOrder?> QueryOrderByIdAsync(long id)
    {
        var orders = await QueryAsync<ProductionOrder>(x => x.Id == id);
        return orders.Count == 0 ? null : orders[0];
    }
    
    // 查询未同步的工单
    public async Task<List<ProductionOrder>> QueryOrderAboutNotSynch()
    {
        var orders = await QueryAsync<ProductionOrder>(x => x.IsSynch != true);
        return orders;
    }
    // 通过机种名称查询机种测试条件
    public async Task<TestConditions?> QueryTestConditionsByNameAsync(string name)
    {
        var testConditions = await QueryAsync<TestConditions>(x => x.Name == name);
        if (testConditions.Count == 0)
        {
            return null;
        }
        else
        {
            InstrumentControlHelper.ParseAutoTransFileContent(testConditions[0].SourceData, out TestConditions t);
            return t;
        }
    }
    
    // 通过ID查询机种测试条件
    public async Task<TestConditions?> QueryTestConditionsByIdAsync(long id)
    {
        var testConditions = await QueryAsync<TestConditions>(x => x.Id == id);
        if (testConditions.Count == 0)
        {
            return null;
        }
        else
        {
            var dbItem = testConditions[0];
            InstrumentControlHelper.ParseAutoTransFileContent(dbItem.SourceData, out TestConditions result);
            // 保留数据库中的其他信息
            result.Id = dbItem.Id;
            result.Remarks = dbItem.Remarks;
            result.CreateTime = dbItem.CreateTime;
            result.ApplicableInstrument = dbItem.ApplicableInstrument;
            return result;
        }
    }
    
    public async Task<List<TestConditions>> QueryParamAboutNotSynch()
    {
        var testConditions = await QueryAsync<TestConditions>(x => x.IsSynch != true);
        return testConditions;
    }

    // 保存工单
    public async Task<bool> SaveProductionOrderAsync(ProductionOrder order)
    {
        // 查询 工单名称+周期 是否有重复
        var exist = await QueryAsync<ProductionOrder>(x => x.Name == order.Name && x.BatchNumber == order.BatchNumber);
        if (exist.Count != 0)
        {
            NotificationHelper.ShowError("保存失败", "同工单下周期号请确保唯一性");
            return false;
        }
        order.Id = SnowFlakeSingle.Instance.NextId();
        order.CreateTime = DateTime.Now;
        var result = await InsertAsync(order);
        return result;
    }

    // 更新工单
    public async Task<bool> UpdateProductionOrderAsync(ProductionOrder order)
    {
        var result = await UpdateAsync(order);
        return result;
    }
    
    public async Task<bool> UpdateTestConditionsAsync(TestConditions p)
    {
        var result = await UpdateAsync(p);
        return result;
    }
    
    // 更新测试明细的同步状态
    public async Task<bool> SetAsyncSuccessFlagById(long id)
    {
        var record = await QueryAsync<TestRecord>(x => x.Id == id);
        if (record.Count == 0)
        {
            return false;
        }
        record[0].IsSynch = true;
        var result = await UpdateAsync(record[0]);
        return result;
    }

    // 删除工单
    public async Task<bool> DeleteProductionOrderAsync(long id)
    {
        var result = await DeleteAsync<ProductionOrder>(x => x.Id == id);
        return result;
    }

    // 保存测试记录
    public async Task<bool> SaveTestProductRecordAsync(ProductInfo record)
    {
        record.Id = SnowFlakeSingle.Instance.NextId();
        record.TestDataDetail.ForEach(x =>
        {
            x.Id = SnowFlakeSingle.Instance.NextId();
            x.ProductId = record.Id;
        });
        var resultMain = await InsertAsync(record);
        var resultSecond = await InsertRangeAsync(record.TestDataDetail);
        return resultMain && resultSecond;
    }

    // 不扫码重测保存测试记录
    public async Task<bool> SaveTestProductRecordAsync(ProductInfo record, long productionId)
    {
        // 删除旧数据
        await DeleteAsync<ProductInfo>(x => x.Id == productionId);
        await DeleteAsync<TestRecord>(x => x.ProductId == productionId);

        record.Id = productionId;
        record.TestDataDetail.ForEach(x =>
        {
            x.Id = SnowFlakeSingle.Instance.NextId();
            x.ProductId = productionId;
        });
        var resultMain = await InsertAsync(record);
        var resultSecond = await InsertRangeAsync(record.TestDataDetail);
        return resultMain && resultSecond;
    }

    // 批量根据Id列表查询工单信息
    public async Task<List<ProductionOrder>> QueryProductionOrdersByIdsAsync(List<long> ids)
    {
        if (ids == null || ids.Count == 0) return new List<ProductionOrder>();
        var orders = await QueryAsync<ProductionOrder>(x => ids.Contains(x.Id));
        return orders;
    }

    // 根据工单名和周期号模糊查询工单
    public async Task<List<ProductionOrder>> QueryProductionOrdersByNameAndBatch(string? name, string? batchNumber)
    {
        var query = _db.Queryable<ProductionOrder>();
        if (!string.IsNullOrEmpty(name))
            query = query.Where(x => x.Name==name);
        if (!string.IsNullOrEmpty(batchNumber))
            query = query.Where(x => x.BatchNumber==batchNumber);
        return await query.ToListAsync();
    }

    // 根据工单名和周期号精确查询工单
    public async Task<List<ProductionOrder>> AccurateQueryProductionOrdersByNameAndBatch(string? name, string? batchNumber)
    {
        var query = _db.Queryable<ProductionOrder>();
        if (!string.IsNullOrEmpty(name))
            query = query.Where(x => x.Name.Equals(name));
        if (!string.IsNullOrEmpty(batchNumber))
            query = query.Where(x => x.BatchNumber.Equals(batchNumber));
        return await query.ToListAsync();
    }

    // 根据时间范围、ConditionId集合、条码号、测试结果查ProductInfo
    public async Task<List<ProductInfo>> QueryProductInfoByTimeAndConditionIds(DateTime start, DateTime end, List<long> conditionIds, string? barcode, int? result)
    {
        var query = _db.Queryable<ProductInfo>()
            .Where(x => x.StartTime >= start && x.EndTime <= end.AddDays(1));
        if (conditionIds != null && conditionIds.Count > 0)
            query = query.Where(x => conditionIds.Contains(x.ConditionId));
        if (!string.IsNullOrEmpty(barcode))
            query = query.Where(x => x.BarCode.Contains(barcode));
        if (result.HasValue)
            query = query.Where(x => x.Result == result.Value);
        return await query.ToListAsync();
    }

    // 根据时间范围、条码号、测试结果查ProductInfo
    public async Task<List<ProductInfo>> QueryProductInfoByTime(DateTime start, DateTime end, string? barcode, int? result)
    {
        var query = _db.Queryable<ProductInfo>()
            .Where(x => x.StartTime >= start && x.EndTime <= end.AddDays(1));
        if (!string.IsNullOrEmpty(barcode))
            query = query.Where(x => x.BarCode.Contains(barcode));
        if (result.HasValue)
            query = query.Where(x => x.Result == result.Value);
        return await query.ToListAsync();
    }

    // 通过 [条码] 和 [工单编号] 查询测试记录
    public async Task<List<ProductInfo>> QueryProductInfoByBarcodeAndOrder(string barcode, string orderName)
    {
        List<long> orderIds = (await QueryAsync<ProductionOrder>(x => x.Name == orderName)).Select(x => x.Id).ToList();
        var query = _db.Queryable<ProductInfo>()
            .Where(x => x.BarCode == barcode && orderIds.Contains(x.ConditionId));
        return await query.ToListAsync();
    }
}